package com.oymn.myapplication.page;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.oymn.myapplication.R;
import com.oymn.myapplication.utils.HttpCallBackListener;
import com.oymn.myapplication.utils.Url;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;


public class AddFragment extends Fragment {

    private Button execute = null;
    private EditText goods_name = null;
    private EditText goods_introl = null;
    private Button add_img = null;
    private ImageView show_img = null;
    private Button select_book = null;
    private Button select_digital = null;
    private Button select_qita = null;
    private Button select_quanxin = null;
    private Button select_jihuquanxin = null;
    private Button select_qinwei = null;
    private EditText goods_price = null;


    private static int RESULT_LOAD_IMAGE = 10;

    public AddFragment(){
        super(R.layout.fragment_add);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        execute = view.findViewById(R.id.execute);
        goods_name = view.findViewById(R.id.goods_name);
        goods_introl = view.findViewById(R.id.goods_introl);
        add_img = view.findViewById(R.id.add_img);
        show_img = view.findViewById(R.id.show_img);
        select_book = view.findViewById(R.id.book);
        select_digital = view.findViewById(R.id.digital);
        select_qita = view.findViewById(R.id.qita);
        select_quanxin = view.findViewById(R.id.quanxin);
        select_jihuquanxin = view.findViewById(R.id.jihuquanxin);
        select_qinwei = view.findViewById(R.id.qinwei);
        goods_price = view.findViewById(R.id.price);

        execute.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String goodsName = goods_name.getText().toString();
                String goodsIntrol = goods_introl.getText().toString();
                String goodsPrice = goods_price.getText().toString();

                //上传图片
                BitmapDrawable bitmapDrawable = (BitmapDrawable) show_img.getDrawable();
                String imgString = bitmapToString(bitmapDrawable);
                execute_goods(goodsName,goodsIntrol,goodsPrice,imgString);//添加商品到数据库中，相当于发布了

                Toast.makeText(getActivity(),"发布成功",Toast.LENGTH_SHORT).show();
                goods_name.setText("");
                goods_introl.setText("");
                goods_price.setText("0.00");
                show_img.setImageBitmap(null);
            }
        });

        add_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                //这里要传一个整形的常量RESULT_LOAD_IMAGE到startActivityForResult()方法。
                startActivityForResult(intent, RESULT_LOAD_IMAGE);
            }
        });


    }

    //添加商品到数据库中
    void execute_goods(String goodsName,String goodsIntrol,String goodsPrice,String imgString){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost request = new HttpPost(Url.goods_url);
                    request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
                    //封转参数
                    List<NameValuePair> param = new ArrayList<NameValuePair>();
                    param.add(new BasicNameValuePair("action", "execute"));
                    param.add(new BasicNameValuePair("goods_name", goodsName));
                    param.add(new BasicNameValuePair("goods_introl", goodsIntrol));
                    param.add(new BasicNameValuePair("goods_price", goodsPrice));
                    param.add(new BasicNameValuePair("goods_img", imgString));
                    request.setEntity(new UrlEncodedFormEntity(param, HTTP.UTF_8));

                    //获取响应的结果
                    HttpResponse response = httpClient.execute(request);
                    //获取HttpEntity
                    HttpEntity entity = response.getEntity();
                    //获取响应的结果信息
                    String result = EntityUtils.toString(entity, "UTF-8");

                    //这里没获取什么，就这样吧
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }


    //将图片转换为字符串
    public static String bitmapToString(BitmapDrawable drawble) {
        // 保存
        // BitmapDrawable drawble = (BitmapDrawable) cv_head.getDrawable();
        Bitmap bitmap = drawble.getBitmap();

        // 第一步 将bitmap 转换成字节数组输出流
        ByteArrayOutputStream byStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 80, byStream);

        // 利用base64将字节数组转换成字符串
        byte[] byteArray = byStream.toByteArray();
        String imgString = new String(Base64.encodeToString(byteArray, Base64.DEFAULT));
        return imgString;

    }


    //用户选择一张图片，onActivityResult()方法将会被调用，
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == android.app.Activity.RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getActivity().getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();


            InputStream is = null;
            try {
                is = getActivity().getContentResolver().openInputStream(data.getData());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            Bitmap bitmap = BitmapFactory.decodeStream(is);
//            imageView.setScaleType(ImageView.ScaleType.CENTER);
//            Bitmap bitmap=BitmapFactory.decodeFile(picturePath);
            show_img.setImageBitmap(bitmap);
        }
    }

}
